#include "dspSimulator/instruction/MVKL.h"

namespace dspsimulator {
    std::string MVKL::to_string() const {
        return get_standard_condition(m_creg_z) + m_name + " " + get_function_unit_name(m_func_unit) + " " +
               m_op1->to_string() + "," + m_op2->to_string();
    }

    std::shared_ptr<DspInstruction> MVKL::decode_standard_instruction(const std::shared_ptr<DspInstructionInfo> &dsp_instruction_info) {
        std::shared_ptr<MVKL> mvkl;
        std::bitset<32> &data = dsp_instruction_info->m_standard_bits;
        if (common::check_bits<5>(data, 0b01010, 2) &&
            exist_standard_condition(common::extract_bits<4>(data, 28))) {
            // MVK (.unit) scst16, sint
            mvkl = std::make_shared<MVKL>(dsp_instruction_info->address(), 4);
            mvkl->m_creg_z = common::extract_bits<4>(data, 28);
            u32 dst = common::extract_bits<5>(data, 23).to_ulong();
            u32 cst = common::extract_bits<16>(data, 7).to_ulong();
            bool s = data[1];
            mvkl->m_p = data[0];
            mvkl->m_func_unit = s ? FuncUnit::S1 : FuncUnit::S2;
            mvkl->m_op1 = std::make_shared<Immediate32>(common::extract_bit_to_int<16>(cst));
            mvkl->m_op2 = std::make_shared<SingleReg>(get_dst_reg32_kind(dst, s));
        }
        return mvkl;
    }

    void MVKL::generate_ir(const std::shared_ptr<simulator::IRGenElement> &ir_gen_element) {
        std::shared_ptr<simulator::LLVMJit> llvm_jit = ir_gen_element->m_llvm_jit;
        RegIRCopy &reg_ir_copy = ir_gen_element->m_reg_ir_copy;
        std::shared_ptr<llvm::IRBuilder<>> ir_builder = llvm_jit->ir_builder();

        auto cst = std::dynamic_pointer_cast<Immediate32>(m_op1);
        auto dst = std::dynamic_pointer_cast<SingleReg>(m_op2);
        if (cst && dst) {
            u32 scst16 = cst->data();
            std::string dst_name = get_reg_name(dst->reg());
            llvm::Value *dst_ptr = IRGenerator::get_global_value_ptr(llvm_jit, dst_name);
            ir_builder->CreateStore(ir_builder->getInt32(scst16), dst_ptr);
        }
    }
}
